package cn.jzk.mySpringSecurity_noSeparation.SecurityHandler;

import cn.jzk.mySpringSecurity_noSeparation.Common.Enums.AppHttpCodeEnum;
import cn.jzk.mySpringSecurity_noSeparation.Common.Result.ResponseResult;
import cn.jzk.mySpringSecurity_noSeparation.Common.Utils.MyJsonUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录用户【认证失败】响应处理器
 * @author jiangzk
 */
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException{

        // 设置响应的内容类型和字符集
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");

        // 返回自定义的 JSON 响应信息
        try (PrintWriter writer = response.getWriter()) {
            writer.print(MyJsonUtils.stringify(
                    ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR.getCode(),
                            AppHttpCodeEnum.LOGIN_ERROR.getMsg())));
        }
    }
}
